<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin;
use App\Models\SystemConfig;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Auth\Events\Registered;

class RegisterController extends Controller
{
    use RegistersUsers;

    protected $redirectTo = '/admin';

    public function __construct()
    {
        $this->middleware('guest:admin');
    }

    public function showRegistrationForm()
    {
        $systemConfig = SystemConfig::getConfigList();
        return view('admin.register.index', [
            'systemConfig' => $systemConfig
        ]);
    }

    protected function guard()
    {
        return Auth::guard('admin');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param array $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'username' => 'required|string|max:255',
            'account'  => 'required|max:100|unique:admins',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

    /**
     * Handle a registration request for the application.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $this->validator($request->all())->validate();
        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    }

    /**
     * Description:
     * User: Vijay <1937832819@qq.com>
     * Date: 2020/09/11
     * Time: 17:07
     * @param Request $request
     * @return array
     */
    public function ajaxRegister(Request $request)
    {
        try {
            DB::beginTransaction();
            $validator = Validator::make(
                $request->input(), [
                'username' => 'required|string|max:255',
                'account'  => 'required|max:100|unique:admins',
                'password' => 'required|string|min:5|confirmed',
                'captcha'  => 'required|captcha',
            ], [
                'captcha.required' => trans('validation.required'),
                'captcha.captcha'  => trans('validation.captcha'),
            ]);
            if ($validator->fails()) {
                $data = [
                    'code'        => 1,
                    'msg'         => $validator->errors()->first(),
                    'data'        => [],
                    'create_time' => date('Y-m-d H:i:s', time())
                ];
                return response()->json($data);
            }
            $data = [
                'password'   => Hash::make($request->input('password')),
                'username'   => $request->input('username'),
                'tel'        => $request->input('account'),
                'account'    => $request->input('account'),
                'role_names' => 'general_user',
                'status'     => 0,
            ];
            $res  = Admin::query()->create($data);
            $res->assignRole($data['role_names']);
            DB::commit();
            $data = [
                'code'        => 0,
                'msg'         => '注册成功',
                'data'        => [],
                'create_time' => date('Y-m-d H:i:s', time())
            ];
            return response()->json($data);
        } catch (\Exception $e) {
            DB::rollBack();
            $data = [
                'code'        => 1,
                'msg'         => $e->getMessage(),
                'data'        => [],
                'create_time' => date('Y-m-d H:i:s', time())
            ];
            return response()->json($data);
        }
    }

    /**
     * Description:
     * User: Vijay <1937832819@qq.com>
     * Date: 2020/09/11
     * Time: 17:33
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function telCode(Request $request)
    {
        $phone = $request->input('phone');
        if (!preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $phone)) {
            $data = [
                'code'        => 1,
                'msg'         => '请填写正确的手机号码',
                'data'        => [],
                'create_time' => date('Y-m-d H:i:s', time())
            ];
            return response()->json($data);
        }
        $info = Admin::query()->where('account', $phone)->first();
        if ($info) {
            $data = [
                'code'        => 1,
                'msg'         => '该手机号已被注册',
                'data'        => [],
                'create_time' => date('Y-m-d H:i:s', time())
            ];
            return response()->json($data);
        }
        // 存在就不发送
        if (Cache::has($phone)) {
            $code = Cache::get($phone);
        } else {
            //发送验证码
            $code = mt_rand(1000, 9999);
            Cache::put($phone, $code, 60);
        }
        $data = [
            'code' => 0,
            'msg'  => '发送成功',
            'data' => []
        ];
        return $data;
    }

    /**
     * Instructions:Create a new user instance after a valid registration.
     * Author: Vijay  <1937832819@qq.com>
     * Time: 2019/5/7 16:38
     * @param array $data
     * @return mixed
     */
    protected function create(array $data)
    {
        return Admin::create([
            'username' => $data['username'],
            'account'  => $data['account'],
            'password' => Hash::make($data['password']),
        ]);
    }
}
